#include "StdAfx.h"
#include "../Include/SkinAppBase.h"

#include <Util.h>
#include <UIUtil.h>
#include "SkinWndBase.h"

extern MSG g_AppMsg = {0};

//////////////////////////////////////////////////////////////////////////
CSkinAppBase::CSkinAppBase(void)
{
    m_pMainFrame = NULL;
}

CSkinAppBase::~CSkinAppBase(void)
{
}

int CSkinAppBase::Run()
{
    XDIAG_INIT_MAIN_THREAD();
    if(InitInstance())
    {
        RunMessageLoop();
    }
    return ExitInstance();
}

void CSkinAppBase::RunMessageLoop()
{
    IXMsgListenSrv* pMsgListenSrv;
    HRESULT hResult = Util::CreateObject(&pMsgListenSrv);
    XASSERT_ERROR(SUCCEEDED(hResult), _T("Failed to Create IXMsgListenSrv*"));

    LRESULT lResult = 0;
    BOOL bHandled = FALSE;
    // Main message loop:
    BOOL bRet = FALSE;
    while ( (bRet = GetMessage(&g_AppMsg, NULL, 0, 0)))
    {
        if(bRet == -1)
            break;
        if(pMsgListenSrv != NULL)
        {
            lResult = pMsgListenSrv->InvokeMessageFilter((XWND)g_AppMsg.hwnd, g_AppMsg.message, g_AppMsg.wParam, g_AppMsg.lParam, bHandled);
            if(bHandled)
            {
                bHandled = FALSE;
                continue;
            }
        }

        if(PreTranslateMessage(&g_AppMsg))
            continue;

        if(pMsgListenSrv != NULL && g_AppMsg.hwnd == NULL)
        {
            lResult = pMsgListenSrv->InvokeMessageListener((XWND)g_AppMsg.hwnd, g_AppMsg.message, g_AppMsg.wParam, g_AppMsg.lParam, bHandled);
            if(bHandled)
            {
                bHandled = TRUE;
                continue;
            }
        }

        TranslateMessage(&g_AppMsg);
        DispatchMessage(&g_AppMsg);
    }
    if(g_AppMsg.message == WM_QUIT)
    {
        ::PostQuitMessage(g_AppMsg.wParam);
    }
    XSAFE_RELEASE(pMsgListenSrv);
}

BOOL CSkinAppBase::InitInstance()
{
    return TRUE;
}

int CSkinAppBase::ExitInstance()
{
    return 0;
}

void CSkinAppBase::SetMainFrame(IXWindow* pMainFrame)
{
    m_pMainFrame = pMainFrame;
}

IXWindow* CSkinAppBase::GetMainFrame()
{
    return m_pMainFrame;
}

BOOL CSkinAppBase::PreTranslateMessage(MSG* pMsg)
{
    // Only input message need to be handled
    if ((pMsg->message >= WM_KEYFIRST && pMsg->message <= WM_KEYLAST) &&
        (pMsg->message >= WM_MOUSEFIRST && pMsg->message <= WM_MOUSELAST))
    {
        IXWindow* pActWindow = UIUtil::XGetActiveWindow();
        if(pActWindow != NULL && !UIUtil::XIsModelWindow(pActWindow))
            return ::IsDialogMessage((HWND)pActWindow->GetHandle(), pMsg);
    }
    return FALSE;
}
